package com.lly.pro.common;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Hommond
 * @date 2/25/2019
 */
public class Tools {

    public static Field[] getFields(Object object) {
        //获得类
        Class clazz = object.getClass();
        // 获取实体类的所有属性信息，返回Field数组
        return clazz.getDeclaredFields();
    }

    public static Boolean setFieldValueByFieldName(String fieldName, Object object,Object value) {
        try {
            // 获取obj类的字节文件对象
            Class c = object.getClass();
            // 获取该类的成员变量
            Field f = c.getDeclaredField(fieldName);
            // 取消语言访问检查
            f.setAccessible(true);
            // 给变量赋值
            f.set(object, value);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static Set getFieldName(Class clazz){
        Field[] fields = clazz.getDeclaredFields();
        Set set = new HashSet();
        for (Field field : fields){
            set.add(field.getName());
        }
        return set;
    }

    /**
     * 解决attr跟数据库字段的对应关系，将userName转化为user_name
     * @Param attr 类属性 如userName
     * @return AdminInfo
     */
    public static String changeAttrToColumn( String attr ){
        char[] array = attr.toCharArray();
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < array.length; i++){
            if (Character.isUpperCase(array[i])){
                array[i] = Character.toLowerCase(array[i]);
                set.add(i);
            }
        }
        StringBuffer column = new StringBuffer(String.valueOf(array));
        Integer offset = 0;
        for (Integer i : set){
            column.insert(i+offset++,"_");
        }
        return column.toString();
    }

}
